package com.lagou.edu.util;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @author: jie.zhao
 * @create: 2021/07/31 14:31
 */
public class AESUtil {

    private static final byte[] Loginkey = "A172F21EDB30992B24135T8B14505K44".getBytes();
    private static final byte[] Loginiv = "1960434827978590".getBytes();;
    private static final String Loginmode = "AES/CBC/PKCS5Padding";

    public static String LoginEncrypt(String sSrc) {
        String result = null;
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(Loginkey, "AES");
            Cipher cipher = Cipher.getInstance(Loginmode);// "算法/模式/补码方式"
            IvParameterSpec ivParam = new IvParameterSpec(Loginiv);// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParam);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf8"));
            result = Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String LoginDecrypt(String sSrc) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(Loginkey, "AES");
            Cipher cipher = Cipher.getInstance(Loginmode);
            IvParameterSpec ivParam = new IvParameterSpec(Loginiv);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParam);
            byte[] encrypted1 = Base64.getDecoder().decode(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}

